//
//  UIViewController.swift
//  ss-2t-ios-app
//
//  Created by 胡秋生 on 2019/5/30.
//  Copyright © 2019 胡秋生. All rights reserved.
//

import Foundation
import UIKit
// 扩展UIViewController 类型
extension UIViewController: ShouldPopDelegate {

   public func CGFloatAutoFit(_ float: CGFloat, _ width: CGFloat = 375) -> CGFloat {
        let min = UIScreen.main.bounds.height < UIScreen.main.bounds.width ? UIScreen.main.bounds.height : UIScreen.main.bounds.width
        return min / width * float
    }
    // MARK:用户监听系统返回键
    public func currentViewControllerShouldPop() -> Bool {
         true
    }
    
    public  func navigationShouldPop() -> Bool{
           true
    }
}

extension UINavigationController: UINavigationBarDelegate,UIGestureRecognizerDelegate {

    // MARK: 打开新的界面，并关闭原来的界面,相当于html中的重定向
    func pushRedirectViewController(_ viewController: UIViewController, animated: Bool) {
        //获取当前UINavigationController 中的UIViewController堆栈
        let viewControllers = self.viewControllers
        // 重新创建一个新的UIViewController  堆栈
        var newViewControllers: [UIViewController] = []
        // 除了最后一个UIViewController （即当前界面）以外，其他的UIViewController都添加到新的UIViewController堆栈中
        for i in 0..<viewControllers.count - 1 {
            newViewControllers.append(viewControllers[i])
        }
        // 把要打开的UIViewController 添加到堆栈中的最后一个
        newViewControllers.append(viewController)
        // 重新设置新的UINavigationController 的UIViewController堆栈
        self.setViewControllers(newViewControllers, animated: animated)
    }

    // MARK: 打开新界面，关闭指定UIViewController在当前UINavigationController的UIViewController堆栈中的所有页面
    // 如：堆栈如下：[AViewController,AViewController,BViewController,BViewController]
    // 启动新界面CViewController时要关闭所有的BViewController，此时的堆栈为[AViewController,AViewController,CViewController]
    func pushReLaunchViewController<T: UIViewController>(_ viewController: T, animated: Bool) {
        //获取当前UINavigationController 中的UIViewController堆栈
        let viewControllers = self.viewControllers
        // 重新创建一个新的UIViewController  堆栈
        var newViewControllers: [UIViewController] = []
        // 除了最后一个UIViewController （即当前界面）以外，其他的UIViewController都添加到新的UIViewController 堆栈中
        for i in 0..<viewControllers.count - 1 {
            // 不添加T对应的子类
            if !(viewControllers[i] is T) {
                newViewControllers.append(viewControllers[i])
            }
        }
        // 把要打开的UIViewController 添加到堆栈中的最后一个
        newViewControllers.append(viewController)
        // 重新设置新的UINavigationController 的UIViewController堆栈
        self.setViewControllers(newViewControllers, animated: true)
    }

    public func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool {
        // 看一下当前控制器有没有实现代理方法 currentViewControllerShouldPop
        // 如果实现了，根据当前控制器的代理方法的返回值决定
        if viewControllers.count < (navigationBar.items?.count)! {
            return true
        }
        var shouldPop = false
        let vc: UIViewController = topViewController!
        if vc.responds(to: #selector(currentViewControllerShouldPop)) {
            shouldPop = vc.currentViewControllerShouldPop()
        }
        if shouldPop {
            DispatchQueue.main.async {
                self.popViewController(animated: true)
            }
        } else {
            for subview in navigationBar.subviews {
                if 0.0 < subview.alpha && subview.alpha < 1.0 {
                    UIView.animate(withDuration: 0.25) {
                        subview.alpha = 1.0
                    }
                }
            }
        }
        return false
    }
    public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        if childViewControllers.count == 1 {
            return false
        } else {
            if topViewController?.responds(to: #selector(navigationShouldPop)) != nil {
                return topViewController!.navigationShouldPop()
            }
            return true
        }
    }
}

@objc protocol ShouldPopDelegate {
    // MARK: 点击系统返回键时回调
    @objc optional func currentViewControllerShouldPop() -> Bool
    @objc optional func navigationShouldPop() -> Bool
}
